﻿using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet;
using MauiAppClient.ViewModel;
using System.Text;
using System.Timers;
using MQTTnet.Server;

namespace MauiAppClient
{
    public partial class MainPage : ContentPage
    {
        public static IMqttClient _mqttClient;
        public MainPageModel _vm;
        public MainPage(MainPageModel vm)
        {
            InitializeComponent();
            _vm = vm;
            BindingContext = _vm;
            MqttInit();


            System.Timers.Timer myTimer = new System.Timers.Timer();
            myTimer.Elapsed += new ElapsedEventHandler(PollingEvent);
            // 1000 ms is one second
            myTimer.Interval = 1000;
            myTimer.Start();
        }

        private void PollingEvent(object sender, ElapsedEventArgs e)
        {
            _vm.StrTime = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
        }

        /// <summary>
        /// 初始化MQTT
        /// </summary>
        public void MqttInit()
        {
            string clientId = Guid.NewGuid().ToString();
            var optionsBuilder = new MqttClientOptionsBuilder()
                .WithTcpServer("114.115.132.167", 1883) // 要访问的mqtt服务端的 ip 和 端口号
                                                        //.WithCredentials("admin", "123456") // 要访问的mqtt服务端的用户名和密码
                .WithClientId(clientId) // 设置客户端id
                .WithCleanSession()
                .WithTls(new MqttClientOptionsBuilderTlsParameters
                {
                    UseTls = false  // 是否使用 tls加密
                });

            var clientOptions = optionsBuilder.Build();
            _mqttClient = new MqttFactory().CreateMqttClient();
            _mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync; // 客户端连接成功事件
            _mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync; // 客户端连接关闭事件
            _mqttClient.ApplicationMessageReceivedAsync += _mqttClient_ApplicationMessageReceivedAsync; // 收到消息事件
            _mqttClient.ConnectAsync(clientOptions);
        }

        /// <summary>
        /// 客户端连接关闭事件
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private Task _mqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        {
            _vm.StrTips = "已断开与服务端的连接";
            int i = 0;
            Task.Factory.StartNew(() =>
            {
                while (_mqttClient.IsConnected == false)
                {
                    i++;
                    _vm.StrTips = "尝试重新连..." + i;
                    Thread.Sleep(5 * 1000);
                    _mqttClient.ConnectAsync(_mqttClient.Options);
                    _mqttClient.SubscribeAsync("pc-helper", MqttQualityOfServiceLevel.AtLeastOnce);
                }
            }).ConfigureAwait(false);

            return Task.CompletedTask;
        }

        /// <summary>
        /// 客户端连接成功事件
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private Task _mqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
        {
            _vm.StrTips = "已连接服务端";
            _mqttClient.SubscribeAsync("pc-helper", MqttQualityOfServiceLevel.AtLeastOnce);

            return Task.CompletedTask;
        }
        /// <summary>
        /// 收到消息事件
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        {
            string msg = Encoding.UTF8.GetString(arg.ApplicationMessage.Payload);
            var model = Newtonsoft.Json.JsonConvert.DeserializeObject<MsgModel>(msg);
            _vm.StrKey = "词语：" + model.query?.ToString();

            string value1 = "翻译：";
            if (model.translation != null)
            {
                foreach (var item in model.translation)
                {
                    value1 += item;
                }
            }
            _vm.StrValue1 = value1;

            string value2 = "解释：";
            if (model.basic != null && model.basic.explains != null)
            {
                foreach (var item in model.basic.explains)
                {
                    value2 += item;
                }
            }

            _vm.StrValue2 = value2;
            return Task.CompletedTask;
        }

        public void Publish(string data)
        {
            var message = new MqttApplicationMessage
            {
                Topic = "pc-helper",
                Payload = Encoding.Default.GetBytes(data),
                QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
                Retain = true  // 服务端是否保留消息。true为保留，如果有新的订阅者连接，就会立马收到该消息。
            };
            _mqttClient.PublishAsync(message);
        }
    }
}